<template>
  <view class="container">
    <u-navbar :is-back="false" title="添加客户"
      title-size="30"
      :background="{background:'#2B88FE' }"
      title-color="#fff">
      <div class="head_icon">
        <u-icon @click="$api.handleBackTo"
          name="arrow-left" color="#fff"
          size="36">
        </u-icon>
        <u-icon @click="$api.handleHomeTo"
          name="home" color="#fff" size="36">
        </u-icon>
      </div>
    </u-navbar>
    <!-- 输入框区域 -->
    <view class="content">


		
		
      <u-form :model="form" :rules="rules"
        ref="uForm" label-width="180rpx">
		
		<u-form-item label="区域">
		  <div class="boxFlex"
		    @click="areaShow=!areaShow">
		    <span
		      class="title">{{areaText}}</span>
		    <u-icon name="arrow-right"
		      color="#999">
		    </u-icon>
		  </div>
		  <div class="areaDialog" v-if="areaShow">
		    <view class="area-list">
		      <view class="li_area"
		        v-for="(item,index) in Areavalue"
		        :key="index">
		      
		        <view
		          @click="setArea(index,v.fId)"
		          :class="{'active_area':v.fId===formActive[index]}"
		          class="cell_area"
		          v-for="(v,i) in item" :key="i">
		          {{v.fNm}}
		        </view>
		      </view>
		    </view>
		    <u-button type="primary"
		      @click="areaConfirm">确定
		    </u-button>
		  </div>
		  
		</u-form-item>
		
        <u-form-item label="超市名称" prop="Name">
          <input type="text"
            placeholder="请输入超市名称 " 
			  @blur="getMarkName"
            v-model="form.Name"/>
        </u-form-item>
        <u-form-item label="联系人" prop="Contacts">
          <input type="text"
            placeholder="请输入联系人姓名 (或尊称) "
            v-model="form.Contacts" />
        </u-form-item>
        <u-form-item label="联系电话" prop="Tell">
          <input type="text" placeholder="联系电话 "
            v-model="form.Tell" />
        </u-form-item>
        <u-form-item label="联系人备注"
          prop="TellInfo">
          <input type="text" placeholder="联系人备注 "
            v-model="form.TellInfo" />
        </u-form-item>
        <u-form-item label="超市类型">
          <picker mode="selector"
            :range="ClassMktvalue"
            @change="bindClassMarket"
            range-key="fClassName">
            <div class="boxFlex">
              {{ClassMktText}}
              <u-icon name="arrow-right"
                color="#999">
              </u-icon>
            </div>
          </picker>
        </u-form-item>
        <u-form-item label="超市规模">
          <picker mode="selector"
            :range="Sizevalue"
            @change="bindSizeMarket"
            range-key="fClassName">
            <div class="boxFlex">
              {{SizeText}}
              <u-icon name="arrow-right"
                color="#999">
              </u-icon>
            </div>
          </picker>
        </u-form-item>


        <u-form-item label="是否老客户">
          <div @click="showClient=true"
            class="boxFlex">
            {{OldText}}<u-icon name="arrow-right"
              color="#999">
            </u-icon>
          </div>
          <u-picker mode="selector"
            v-model="showClient" :range="wheList"
            @confirm="bindClient">
          </u-picker>
        </u-form-item>
        <u-form-item label="是否已签约">
          <div @click="signClient=true"
            class="boxFlex">
            {{SignText}}<u-icon name="arrow-right"
              color="#999">
            </u-icon>
          </div>
          <u-picker mode="selector"
            v-model="signClient" :range="signList"
            @confirm="bindIsSign">
          </u-picker>
        </u-form-item>
        <u-form-item label="选择地址">
          <div class="boxFlex" @click="chooseMap">
            {{form.Street}}
            <u-icon name="arrow-right"
              color="#999">
            </u-icon>
          </div>
          <!-- <u-picker mode="region" v-model="show" @confirm="bindProvinces">
        </u-picker> -->
        </u-form-item>
        <u-form-item label="详细地址">
          <input type="text" placeholder="详细地址"
            v-model="form.Address" />
        </u-form-item>
      </u-form>
    </view>

    <!-- 上传商家门头照片 -->
    <view class="choo_content">
      <view class="bill">
        <view class="cle_content">
          <view class="title">
            拍照上传超市门头照片
          </view>
          <view class="seller"
            @click="photoCreate">
            <image v-if="form.Pic" :src="form.Pic"
              mode="" />
            <u-icon v-else name="plus"></u-icon>
          </view>
          <photoLoaction v-if="showpho"
            @getPhotoSuccess="getPhotoSuccess"
            @getPhotoFail="getPhotoFail"
            :address="urlimg"></photoLoaction>
        </view>
        <view v-for="(item,index) in clients"
          :key="index">
          <view class="uncleared">
            <view class="uncle">
              未结清账单{{index}}
            </view>
            <view class="dele"
              @click="clients.splice(index,1)">
              删除</view>
          </view>
          <view class="cleItem">
            <view class="name">
              账单金额</view>
            <input type="text"
              placeholder="请输入账单金额"
              v-model="item.Money" />
          </view>
          <view class="cleItem">
            <view class="name">备注
            </view> <input type="text"
              placeholder="请输入账单备注信息"
              v-model="item.fInfo" />
          </view>
          <view class="cle_content">
            <view class="title">
              账单图片
            </view>
            <u-upload :header="header"
              :max-count="1" :action="action"
              :auto-upload="true"
              :ref="'upload' +index">
            </u-upload>
          </view>
        </view>
        <view class="addtitle" @click="addClient">
          +
          添加老客户未结清账单</view>
      </view>

      <view class="details">
        <view class="detaItem">
          <view class="title">
            促销情况</view>
          <u-input type="textarea" border value=""
            placeholder="请输入内容"
            v-model="form.SalesInfo" />
        </view>
        <view class="detaItem">
          <view class="title">
            历史销售数据</view>
          <u-input type="textarea" border value=""
            placeholder="请输入内容"
            v-model="form.Analysis" />
        </view>
        <view class="detaItem">
          <view class="title">
            备注</view>
          <u-input type="textarea" border value=""
            placeholder="请输入内容"
            v-model="form.Remarks" />
        </view>
      </view>
      <button type="primary"
        @click="handleAdd">添加客户</button>
    </view>

  </view>
</template>

<script>
import photoLoaction from '@/components/photoLoaction'
export default {
  components: { photoLoaction },
  data() {
    return {
      showpho: false,
      rules: {
        Name: [
          {
            required: true,
            message: '请输入超市名称',
            trigger: ['change', 'blur']
          }
        ],
        Contacts: [
          {
            required: true,
            message: '请输入联系人姓名',
            trigger: ['change', 'blur']
          }
        ],
        Tell: [
          {
            required: true,
            message: '请输入手机号',
            trigger: ['change', 'blur']
          }
          //,
          //{
          //  validator: (rule, value, callback) => {
          //    return this.$u.test.mobile(value)
          //  },
          // message: '手机号码不正确',
          // trigger: ['change', 'blur']
          //}
        ]
      },
      header: {
        token: uni.getStorageSync('token')
      },
      action: this.urlimg + 'api/Upfile/PostImgFile',
      params: {
        province: true,
        city: true,
        area: true
      },
	  formActive: {
	    0: '',
	    1: '',
	    2: ''
	  },
      clineOnce: true,
      fClassId: {},
  
      AreavalueData: [],
      clients: [],
      areaList: [],
      showClient: false,
      signClient: false,
      areaShow: false,
      show: false,
      OldText: '请选择是否是老客户',
      SignText: '请选择是否是已成交',
      form: {
        Pic: '',
        Name: '',
        Contacts: '',
        Tell: '',
        TellInfo: '',
        ClassSizeId: 0,
        ClassMktId: 0,
        ClassAreaId: 0,
        IsOld: '',
        IsSign: '',
        Map: '',
        Street: '请选择所在地址',
        Address: '',
        SalesInfo: '',
        Analysis: '',
        Remarks: '',
        BuyCount: '',
        BuyMoney: '',
        BuyProCount: ''
      },
      areaText: '请选择区域',
      Areavalue: [], //存储超市规模数据
      SizeText: '请选择超市规模',
      Sizevalue: [], //存储超市规模数据
      ClassMktText: '请选择超市分类',
      ClassMktvalue: [], //存储超市规模数据
      index: '', //超市规模当前选择项
      Provinces: null, //存储省市区选中事件
      ImgList: null,
      wheList: ['不是', '是'], //是否是老客户
      signList: ['未成交', '已成交'], //是否是老客户
      user: {}
    }
  },
 
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },
  mounted() {
    // this.$api.getUserLoacation(res => {
    //   this.form.Map = res.longitude + ',' + res.latitude
    //   this.form.Street = res.result.address
    // })
    this.user = uni.getStorageSync('user_info')
    this.addClient()
 
 this.$axios('api/BusClassArea/GetSClassList', 'post', { value: 0 }).then(res => {
   let info = res.Value[0]
   this.Areavalue = this.getarea(res.Value, info.fId)
   this.AreavalueData = this.getParentNodes(res.Value)
   setTimeout(() => {
     this.setArea(0, info.fId)
   }, 100)
 })
 
    this.$axios('api/MrkClassSize/ListPaged', 'post', { value: 0 }).then(res => {
      let info = res.Value[0]
      this.Sizevalue = res.Value
      this.SizeText = info.fClassName
      this.form.ClassSizeId = info.fClassId
    })
    this.$axios('/api/MrkClassBasic/GetList', 'post', { value: 0 }).then(res => {
      let info = res.Value[0]
      this.ClassMktvalue = res.Value
      this.ClassMktText = info.fClassName
      this.form.ClassMktId = info.fClassId
    })
  },
  methods: {
    photoCreate() {
      this.showpho = true
    },
    getPhotoFail() {
      this.showpho = false
    },
    getPhotoSuccess(e, img) {
      this.form.Street = e.address
      this.form.Map = Object.values(e.location).reverse().toString()
      this.form.Pic = this.urlimg + img
    },
	
	allShow(idx) {
	  if (idx === 0) {
	    this.clearAreaMarket()
	  } else {
	    this.fClassId = this.formActive[idx - 1]
	    this.areaConfirm()
	  }
	},
	areaConfirm() {
	  const info = this.getIdData(this.fClassId)
	  this.areaText = info.fNm
	  this.form.ClassAreaId = info.fId
	  this.areaShow = false
	},
	getParentNodes(list) {
	  let max = Math.max.apply(
	    this,
	    list.map(x => x.fL)
	  )
	  let arr = []
	  for (let index = 1; index <= max; index++) {
	    arr.push(list.filter(x => x.fL == index))
	  }
	  return arr
	},
	getarea(list) {
	  let arr = this.getParentNodes(list)
	    // .map(x => x.map(x => x.fClassName))
	    .filter(x => x.length)
	  // arr.forEach((v, i) => {
	  //   if (i > 0) v = []
	  // })
	  return arr
	},
	getParentId(id) {
	  return this.AreavalueData.flat().filter(x => x.fPId == id)
	},
	getIdData(id) {
	  // let { column, value } = e.detail
	  // let c = this.Areavalue[column][value]
	  const arr = this.AreavalueData.flat()
	  let info = arr.find(x => x.fId === id)
	  return info
	},
	getNameData(name) {
	  // let { column, value } = e.detail
	  // let c = this.Areavalue[column][value]
	  const arr = this.AreavalueData.flat()
	  let info = arr.find(x => x.fNm === name)
	  return info
	},
	setArea(column, fClassId) {
	  let col = column + 1
	  let child = this.getParentId(fClassId)
	  this.fClassId = fClassId
	  this.formActive[column] = fClassId
	  if (child.length) {
	    this.$set(this.Areavalue, col, child)
	    this.setArea(col, child[0].fId)
	  } else {
	    this.Areavalue = this.Areavalue.slice(0, col)
	  }
	},
	ChangeArea(e) {
	  let info = this.getinfo(e)
	  this.setArea(e.detail.column, info.fId)
	},
	clearAreaMarket() {
	  this.areaText = '请选择区域'
	  this.form.iClassId = 0
	  this.defaultData(() => {
	    // this.$refs.uDropdown.close()
	    this.areaShow = false
	    this.getList()
	  })
	},
	bindAreaMarket(e) {
	  let s = e.detail.value.map((x, i) => this.Areavalue[i][x]).pop()
	  let info = this.AreavalueData.flat().find(x => x.fNm === s)
	  this.areaText = info.fNm
	  this.form.ClassAreaId = info.fId
	  this.defaultData(() => {
	    this.getList()
	  })
	},
	 
    getinfo(e) {
      let { column, value } = e.detail
      let c = this.Areavalue[column][value]
      let info = this.AreavalueData.flat().find(x => x.fNm === c)
      return info
    },
    
    addClient() {
      let info = {
        MrkId: 0,
        MrkName: '',
        Money: '',
        Pic: '',
        fInfo: '',
        WillType: 2
      }
      this.clients.push(info)
    },
    //添加 账单
    addBill() {
      for (let i in this.clients) {
        let dom = this.$refs['upload' + i][0].lists
        if (!dom) {
          uni.showToast({
            title: '请添加账单照片',
            duration: 2000,
            icon: 'none'
          })
          return false
        }
        let img = dom.map(x => x.response.Value[0].sFileUrl).join(',')
        this.clients[i].Pic = img
      }
      this.form.nopaywill = this.clients
    },
    //添加客户
    handleAdd() {
      if (!this.clineOnce) 
	  {
	    uni.showToast({
	      title: '信息提交中，请勿重复提交',
	      icon: 'none',
	      duration: 2000
	    })
	    return false
	  }
	  
      this.clineOnce = false
      this.$refs.uForm.validate(valid => {
        if (valid) {
          //添加未结清账单
          this.addBill()
          let info = JSON.parse(JSON.stringify(this.form))
          info.Street = info.Street.toString()
          //添加客户
          this.$axios('api/MrkBasic/AddDetail', 'post', { value: info }).then(res => {
            if (!res.Success) {
              uni.showToast({
                title: '提交失败：' + res.Message,
                icon: 'none',
                duration: 2000
              })
              this.clineOnce = true
              return false
            }
            this.clineOnce = true
             this.$api.switchTabToUrl('添加客户成功', '/pages/client/client')
          })
        }
      })
    },
    // 超市规模发生改变时触发的事件
    bindSizeMarket(event) {
      let info = this.Sizevalue[event.detail.value]
      this.SizeText = info.fClassName
      this.form.ClassSizeId = info.fClassId
    },
    chooseMap() {
      uni.chooseLocation({
        success: res => {
          this.form.Street = res.address
          this.form.Map = res.longitude + ',' + res.latitude
        }
      })
    },

    bindClassMarket(event) {
      let info = this.ClassMktvalue[event.detail.value]
      this.ClassMktText = info.fClassName
      this.form.ClassMktId = info.fClassId
    },
	getMarkName(event)
	{
		let MarkName=this.form.Name;
		this.$axios('api/MrkBasic/CheckMarkData', 'post', { value: MarkName }).then(res => {
		  if (!res.Success) {
		    uni.showToast({
		      title: '提示：' + MarkName  + res.Message,
		      icon: 'none',
		      duration: 2000
		    })
		    this.clineOnce = false
		  }
		  else{
			   this.clineOnce = true
		  }
		})
	},

    //选择客户发生变化
    bindClient(event) {
      let isClient = Number(event.toString())
      this.form.IsOld = isClient ? 10 : 1
      this.OldText = isClient ? '是' : '不是'
    },
    bindIsSign(event) {
      let isSign = Number(event.toString())
      this.form.IsSign = isSign ? 10 : 1
      this.SignText = isSign ? '已成交' : '未成交'
    },
    //省市区发生改变时触发的事件
    bindProvinces(event) {
      this.form.Street = Object.values(event)
        .map(x => x.label)
        .toString()
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  // background-color: #fff;
  // min-height: 100vh;
  padding-bottom: 120rpx;
  position: relative;
  padding: 30rpx;
  .header {
    color: #0297d7;
    font-weight: 700;
    margin: 0 0 20rpx 45rpx;
    font-size: 26rpx;
  }

  .content {
    background-color: #fff;
    padding: 0 30rpx;
    margin-bottom: 20rpx;
    input {
      opacity: 0.9;
      font-size: 24rpx;
      width: 100%;
      height: 100%;
    }
    .flexbox {
      display: flex;
      align-items: center;

      .uni-input {
        padding: 20rpx;
        text-align: center;
        margin-right: 20rpx;
      }
    }
  }

  //上传图片区域
  .choo_content {
    .choo_box {
      margin: 15rpx 0rpx 10rpx;
      width: 180rpx;
      height: 180rpx;
      border-radius: 6rpx;
      border: 2rpx dashed #c0c0c0;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .text {
        text-align: center;
      }

      .append {
        font-size: 60rpx;
        margin-top: -30rpx;
      }

      .choice {
        font-size: 26rpx;
      }
    }
  }

  .bill {
    .addtitle {
      background-color: #fff;
      color: #64a8fe;
      text-align: center;
      padding: 20rpx;
      font-size: 28rpx;
    }

    .uncleared {
      background-color: #f4fcff;
      color: #999;
      font-size: 24rpx;
      display: flex;
      justify-content: space-between;
      padding: 20rpx 30rpx;
    }

    .cleItem {
      display: flex;
      background-color: #fff;
      margin-bottom: 2rpx;
      padding: 10rpx 30rpx;
      height: 80rpx;
      display: flex;
      align-items: center;
      font-size: 26rpx;

      .name {
        width: 26%;
      }

      input {
        font-size: 25rpx;
      }
    }

    .cle_content {
      background-color: #fff;
      padding: 35rpx 30rpx 10rpx;
      .title {
        font-size: 26rpx;
      }
      .choo_box {
        background-color: #f4f5f6;
        border: 0;
        margin: 0;
        margin: 40rpx 10rpx 0rpx;
        .text {
        }
      }
    }
  }
  .details {
    .detaItem {
      background-color: #fff;
      border-radius: 10rpx;
      margin: 30rpx 0;
      height: 240rpx;
      padding: 20rpx;
      box-sizing: border-box;
      .title {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 15rpx;
      }
      textarea {
        width: 100%;
        height: 160rpx;
        font-size: 28rpx;
      }
    }
  }
  .seller {
    width: 110px;
    height: 110px;
    line-height: 110px;
    color: #606266;
    font-size: 26px;
    margin: 10rpx;
    background: #f4f5f6;
    text-align: center;
    image {
      width: 100%;
      height: 100%;
    }
  }
  .pickerLog {
    width: 100%;
    text-align: center;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 0;
    z-index: 99;
    background-color: rgba(245, 245, 245, 1);
    font-size: 28rpx;
    .answer {
      background-color: #fff;
    }
    .regular {
      height: 90rpx;
      line-height: 90rpx;
      border-bottom: 2rpx solid #eee;
    }
    .colr {
      color: #bdbdbd;
    }
    .prno {
      height: 100rpx;
      line-height: 100rpx;
      background-color: #fff;
      margin-top: 10rpx;
    }
  }
  .active {
    height: 390rpx;
    transition: 0.5s;
  }
  .bg {
    transition-delay: 0.3s;
    transition: 0.5s;
    position: fixed;
    z-index: 999;
    top: 0;
    right: 0;
    left: 0;
    height: calc(100% - 390rpx);
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
  }
}
picker {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
}
.seller {
  background-color: #fff;
}
.boxFlex {
  display: flex;
  justify-content: space-between;
  color: #888;
  padding-right: 20rpx;
  width: 100%;
  font-size: 24rpx;
}



.client-head {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 15rpx;
  background: #fff;
  z-index: 11;

  .lf {
    font-size: 24rpx;
    margin-right: 15rpx;

    .title {
      margin: 0 10rpx;
    }
  }
  u-search {
    width: 65vw;
  }
}


.searchBox {
  padding: 20rpx 32rpx;
  box-sizing: border-box;
}


.areaDialog {
  position: absolute;
  left: 0;
  top: 100rpx;
  width: 100%;
  z-index: 9;
}
.area-list {
  display: flex;
  background-color: #fff;
  font-size: 22rpx;
  .li_area {
    padding: 0rpx;
    height: 60vh;
    overflow: auto;
    flex-grow: 1;
    .cell_area {
      padding: 0rpx;
    }
    // .cell:hover {
    //   background-color: #eee;
    // }
  }
  .li_area:not(:first-child) {
    border-left: 1px solid #eee;
  }
  .active_area {
    background-color: #eee;
    color: #169bd5;
  }

  .cred {
    background-color: #ff0000;
    color: #fef0f0;
  }
}
</style>
